/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.store.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.common.util.ListUtil;
import com.javaeye.store.dto.MaterialsSKUDetail;

public class MaterialsSKUDetailDAOHibernate extends HibernateDaoSupport  implements MaterialsSKUDetailDAO {
	
	/**
	 * 取得在库品的SKU
	 * @param code 在库品SKU ID
	 * @return 实时库存数量
	 */
	//@SuppressWarnings("unchecked")
	public MaterialsSKUDetail getMaterialsSKUDetail(int id) {
		MaterialsSKUDetail skuDetail = (MaterialsSKUDetail)getHibernateTemplate().get(MaterialsSKUDetail.class, id);
		Hibernate.initialize(skuDetail.getMaterials());
		return skuDetail;
	}
	
	public void saveMaterialsSKUDetail(MaterialsSKUDetail detail) {
		getHibernateTemplate().saveOrUpdate(detail);
	}
	
	/**
	 * 需要退供应商的在库品
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<MaterialsSKUDetail> getNeedDefectiveMaterials() {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				//fetch 强制抓去关联对象
				final String queryString = "from MaterialsSKUDetail d join fetch d.materials m"
					 	+ " where d.defectiveNumber > 0"
					 	+ " and d.inuse=1 and m.rootCategory.id in (:ids)"
					 	+ " order by d.id";
				Query query = session.createQuery(queryString);
				query.setParameterList("ids", ListUtil.MATERIALS_CATEGORY_PROCUREMENT);
				return query.list();
			}
		};
		List result = getHibernateTemplate().executeFind(action);
		return result;
	}
	
	/**
	 * 取得所有使用中的在库品
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<MaterialsSKUDetail> getInuseMaterials() {
		final String queryString = "from MaterialsSKUDetail m where m.inuse=1 order by m.id";
		List result = getHibernateTemplate().find(queryString);
		return result;
	}
}
